import * as API from '../../../api/contactsApi';
import * as util from '../../../utils/util';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //性别
    items: [{
        name: '1',
        value: '先生',
        checked: true
      },
      {
        name: '2',
        value: '女士'
      }
    ],
    phoneErrorMsg: "",
    emailErrorMsg: "",
    //id
    //手机
    telephone: '',
    //客户公司名称
    customName: '',
    //客户公司ID
    customId: '',
    //姓名
    name: '',
    //称呼
    sex: '',
    //邮箱
    email: '',
    //部门
    dept: '',
    //职务
    position: '',
    //来源
    createWay: '1',
    selectCustom: ''
  },
  // 提交表单
  formSubmit: function (e) {
    if (validForm(e, this.data.customId)) {
      var postbody = {
        telephone: e.detail.value.telephone,
        customName: this.data.customName,
        customId: this.data.customId,
        name: e.detail.value.name,
        sex: e.detail.value.sex,
        email: e.detail.value.email,
        dept: e.detail.value.dept,
        position: e.detail.value.position,
        createWay: '1'
      };

      API.saveContacts(postbody).then(res => {
        wx.navigateBack({});
        wx.showToast({
          icon: 'success',
          title: '添加成功',
          duration: 1500
        });
        wx.removeStorageSync('contactsAddData');
        wx.removeStorageSync('contact_add_custom_name');
        wx.removeStorageSync('contact_add_custom_id');
      }, err => {
        wx.hideLoading();
        wx.showToast({
          icon: 'none',
          title: err || '添加失败'
        });
      })
    }
  },
  sexChange: function (e) {
    sex: e.detail.value;
    return e.detail.value;
  },

  // 手机号校验
  phoneInput: function (e) {
    var value = e.detail.value;
    if (!validatePhone(value)) {
      this.setData({
        phoneErrorMsg: "请输入正确的手机号"
      });
    } else {
      this.setData({
        phoneErrorMsg: "",
        emailErrorMsg: "",
        phone: value
      });
    }
  },
  //邮箱验证
  emailInput: function (e) {
    var value = e.detail.value;
    if (!validateEmail(value)) {
      this.setData({
        emailErrorMsg: "请输入正确的邮箱"
      });
    } else {
      this.setData({
        emailErrorMsg: "",
        phone: value
      });
    }
  },
  onInputBlur: function () {
    this.setData({
      isTextRight: true
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.addCustomer(options);
  },

  addCustomer:function(options){
    let customId = wx.getStorageSync('contact_add_custom_id');
    let customName = wx.getStorageSync('contact_add_custom_name');
    if (customId) {
      this.setData({
        customName: customName,
        customId: customId,
      });
    }
    if (options && options.selectCustom) {
      this.setData({
        selectCustom: options.selectCustom
      })
    }
    if (options.customId) {
      wx.getStorage({
        key: 'contactsAddData',
        success: function (res) {
          this.setData({
            telephone: res.data.telephone || '',
            customName: customName || res.data.customName || '',
            customId: customId || res.data.customId || '',
            name: res.data.name || '',
            sex: res.data.sex || '',
            email: res.data.email || '',
            dept: res.data.dept || '',
            position: res.data.position || ''
          })
        }
      })
    }
    wx.removeStorageSync('contactsAddData');
    wx.removeStorageSync('contact_add_custom_name');
    wx.removeStorageSync('contact_add_custom_id');
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {
    let contact_add_custom_id = wx.getStorageSync('contact_add_custom_id');
    let contact_add_custom_name = wx.getStorageSync('contact_add_custom_name');

    if (contact_add_custom_id) {
      this.setData({
        customName: contact_add_custom_name,
        customId: contact_add_custom_id
      })
    }
    if (options && options.selectCustom) {
      this.setData({
        selectCustom: options.selectCustom
      })
    }
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.removeStorageSync('contactsAddData');
    wx.removeStorageSync('contact_add_custom_name');
    wx.removeStorageSync('contact_add_custom_id');
  },


  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  gotoCompany: function (e) {
    util.preventMoreClick(this, () => {
      var currentIndex = this.data.customId;
      wx.setStorage({
        key: 'contactsAddData',
        data: this.data,
      })
      wx.navigateTo({
        url: '../contactsCustomer/contactsCustomer?currentIndex=' + currentIndex
      });
    })
  },
  verification: function (e) {
    var name = e.currentTarget.dataset.name;
    this.setData({
      [name]: e.detail.value.replace(/\s+/g, '')
    });
  }
})

function validatePhone(value) {
  if (!value || value.length < 1) {
    return false;
  }
  if (!(util.validators.phone.test(value))) {
    return false;
  }
  return true;
}

//提交验证
function validForm(e, customId) {
  var name = e.detail.value.name;
  var telephone = e.detail.value.telephone;
  var email = e.detail.value.email;
  var sex = e.detail.value.sex;

  var valid1 = validatePhone(telephone)
  if (!valid1) {
    wx.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    });
    return false;
  }

  if (!customId || customId < 1) {
    wx.showToast({
      title: '客户公司不能为空',
      icon: 'none'
    });
    return false;
  }

  if (!sex || sex < 1) {
    wx.showToast({
      title: '性别不能为空',
      icon: 'none'
    });
    return false;
  }


  if (!name || name < 1) {
    wx.showToast({
      title: '姓名不能为空',
      icon: 'none'
    });
    return false;
  }

  if (25 < name.length || name.length < 2) {
    wx.showToast({
      title: '姓名长度只能为2~25',
      icon: 'none'
    });
    return false;
  }


  // email != '' && email != null && email != undefined
  if (email.length > 0) {
    var valid2 = validateEmail(email);
    if (!valid2) {
      wx.showToast({
        title: '请输入正确的邮箱',
        icon: 'none'
      });
      return false;
    }
  }
  return true;
}

function validateEmail(value) {
  if (!(util.validators.email.test(value))) {
    return false;
  }
  return true;
}